from machine import Pin
import time


class Debounce:
    """按键消抖"""

    # pin:按键GPIO,  debounce_delay:消抖延迟时间,默认10ms,   pull:上/下拉模式,默认上拉
    def __init__(self, pin, debounce_delay=10, pull=Pin.PULL_UP):
        self.pin = Pin(pin, Pin.IN, pull)
        self._last_state = self.pin.value()  # 记录按键的初始值，方便之后判断是否按下（因为不知道上拉还是下拉）
        self._debounce_delay = debounce_delay
        self._is_pressed_flag = False

    def is_pressed(self):
        if self.pin.value() != self._last_state and not self._is_pressed_flag:  # 按钮刚被按下,且按下标记为False,防止瞬间多次执行
            time.sleep_ms(self._debounce_delay)
            if self.pin.value() != self._last_state:  # 确认按钮仍然被按下
                self._is_pressed_flag = True  # 更新按钮状态为已按下
                # print("按键按下")
                return True
        elif self.pin.value() == self._last_state:  # 按钮释放时重置按钮状态
            self._is_pressed_flag = False


if __name__ == '__main__':
    test_button = Debounce(25)  # L键
    while True:
        if test_button.is_pressed():
            print("按键被按下")
        time.sleep(0.01)
